package daoImpl;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibernateUtil;
import constants.Constants;
import constants.Queries;
import dao.LoteDao;
import entities.Lote;

public class LoteDaoImpl implements LoteDao {

	private static Logger log = Logger.getLogger(LoteDaoImpl.class);

	private static LoteDao loteDaoImpl = null;


	public static LoteDao getInstance(){
		if(loteDaoImpl == null){
			loteDaoImpl = new LoteDaoImpl();			
		}

		return loteDaoImpl;
	}
	
	
	@Override
	public void cadastrarLote(Lote lote) throws HibernateException {
		log.debug("Inicio do metodo LoteDaoImpl.cadastrarLote Iniciando o " +
				"cadastro dos seguintes dados: " + lote);


		Session session =  HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		try{
			session.saveOrUpdate(lote);
			tx.commit();
		}
		catch(HibernateException e){
			log.error(e);
			tx.rollback();
			throw e;
		}
		finally{
			session.close();
		}

	}
	
	@Override
	public Long getProxNumLote() throws HibernateException {
		log.info("Inicio do metodo LoteDaoImpl.getProxNumLote" + Constants.NEW_LINE);
		
		Session session =  HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		try{
			return ((Long)session.createQuery(Queries.RECUPERA_NUM_PROX_LOTE).list().get(0))+1;
		}
		catch(HibernateException e){
			log.error(e);
			tx.rollback();
			throw e;
		}
		finally{
			session.close();
		}
	}

}
